package service

import (
	"github.com/pkg/errors"
	"strconv"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/drive/redis"
	. "zimuzu_cvn_web_api/pkg/e"
)

//轮播图展示时间（秒）
const SlideshowCycleTime = 3

//GetSlideshow 获取轮播图
//Auth: Xu
func GetSlideshow(module int) (slideshowList []model.Slideshow, err error) {
	page := 1
	per := 4
	slideshowList, err = model.GetSlideshow(config.C.DB.DB, module, page, per)
	if err != nil {
		err = errors.New("获取轮播图失败")
	}
	return
}

//SlideShowClickStatistics 首页轮播图点击统计
//Auth: Xu
func SlideShowClickStatistics(id int) (err error) {
	cacheKey := PublicCacheKeyPre + SlideShowClicksRedisKey
	idString := strconv.Itoa(id)
	setKey := cacheKey + "set"
	bo := redis.IsMember(setKey, idString)
	if !bo {
		if _, err = redis.SAdd(setKey, idString); err != nil {
			return
		}
	}
	idKey := cacheKey + idString
	if _, err = redis.Incr(idKey); err != nil {
		Log("err", "点击数缓存自增1失败")
	}
	return err
}

//UpdateSlideShowDb 定时从缓存读取数据更新数据库，并清空缓存
//Auth: Xu
func UpdateSlideShowDb() {
	cacheKey := PublicCacheKeyPre + SlideShowClicksRedisKey
	setKey := cacheKey + "set"
	if redis.Exists(setKey) {
		slideShowIdSlice, _ := redis.SMembers(setKey)
		//遍历轮播图集合
		for _, id := range slideShowIdSlice {
			idKey := cacheKey + id
			if redis.Exists(idKey) {
				clicks, _ := redis.Get(idKey)
				intClicks, _ := strconv.Atoi(clicks)
				intId, _ := strconv.Atoi(id)
				updateErr := model.IncrSlideShowClicks(config.C.DB.DB, intId, intClicks)
				if updateErr == nil {
					redis.UnDelete(idKey)
				}
			} else {
				redis.SRem(setKey, id)
			}
		}
	}
	return
}
